<!-- 发需求 -->
<template>
	<view class="u-p-b-60">
		<view class="page-view">
			<u-form label-width="auto" :model="demForm" ref="demForm" :rules="rules" :error-type="['toast']">
				<u-form-item label-position="top" label="需求标题" required prop="title">
					<u-input type="textarea" :border="true" placeholder="啥能人都有，啥事都能帮，赶快写下你的需求吧。" v-model="demForm.title" height="170"
						:clearable="false" :maxlength="30" />
				</u-form-item>
				<u-form-item label="所属行业" prop="class_two_name" required right-icon="arrow-right">
					<view @click="classPicker=true" class="u-flex-1 align-right">
						<text style="color: #c0c4cc;" v-if="!demForm.class_one_name">请选择</text>
						<text v-else>{{demForm.class_one_name}}</text>
					</view>
				</u-form-item>
				<!-- <u-form-item label="需要服务标签" prop="class_three_name" required right-icon="arrow-right">
					<view @click="opentagPicker" class="u-flex-1 align-right">
						<text style="color: #c0c4cc;" v-if="!demForm.class_three_name">请选择</text>
						<text v-else>{{demForm.class_three_name}}</text>
					</view>
				</u-form-item> -->
				<!-- <u-form-item label="从业经验要求" prop="exp_name" required right-icon="arrow-right">
					<view @click="expPicker=true" class="u-flex-1 align-right">
						<text style="color: #c0c4cc;" v-if="!demForm.exp_name">请选择</text>
						<text v-else>{{demForm.exp_name}}</text>
					</view>
				</u-form-item> -->
				<u-form-item label="帮忙地址" prop="address" required right-icon="arrow-right">
					<view @click="chooseAddress" class="u-flex-1 align-right">
						<text style="color: #c0c4cc;" v-if="!demForm.address">请选择</text>
						<text v-else>{{demForm.address}}</text>
					</view>
				</u-form-item>
				<u-form-item label="帮忙时间" prop="serve_time" required right-icon="arrow-right">
					<view @click="timePicker=true" class="u-flex-1 align-right">
						<text style="color: #c0c4cc;" v-if="!demForm.serve_time">请选择</text>
						<text v-else>{{demForm.serve_time}}</text>
					</view>
				</u-form-item>
				<u-gap height="30" bg-color="#F6F6F6"></u-gap>
				<u-form-item label="我的出价" :border-bottom="false" required>
					<text slot="right" class="u-font-10">平台代开发票</text>
				</u-form-item>
				<u-form-item prop="price">
					<view class="u-flex u-m-b-20">
						<u-button :type="demForm.type==0? 'default':'success'" plain  class="u-m-r-20" @click="demTypeChange(1)" size="medium" shape="circle" hover-class="none">一口价</u-button>
						<u-button :type="demForm.type==1? 'default':'success'" plain @click="demTypeChange(0)" size="medium" shape="circle" hover-class="none">等报价</u-button>
					</view>
					<view class="input-box">
						<text class="u-font-28 u-tips-color">￥</text>
						<view class="u-line"></view>
						<u-input :placeholder="`${config.MIN_PRICE}~${config.MAX_PRICE}元`" type="digit" class="u-flex-1" :disabled="isDisabled"
							v-model="demForm.price" @blur="priceChange" :clearable="false" />
					</view>
				</u-form-item>
				<u-gap height="30" bg-color="#F6F6F6"></u-gap>
				<u-form-item label-position="top" label="详细描述您的需求内容" prop="description" required>
					<u-input type="textarea" :border="true" placeholder="请详细描述你需要帮忙的事情，如有特别要求，请写明" height="354"
						:clearable="false" :show-confirmbar="false" v-model="demForm.description" :auto-height="false"
						:maxlength="500" />
				</u-form-item>
				<u-form-item label-position="top" label="上传图片" prop="image">

					<u-upload ref="image" :source-type="['album']" width="136" height="136" max-count="9"
						:action="$u.api.uploadUrl()" :header="$u.api.headerConfig()" name="pics" :formData="{filename: 'pics'}"
						:custom-btn="true" @on-uploaded="uploadImageHandle" index="image" :file-list="demForm_image"
						@on-remove="removeImage">
						<view slot="addBtn" class="u-m-l-10"><u-image src="/static/upload.png" mode="aspectFill" width="136"
								height="136"></u-image></view>
					</u-upload>

				</u-form-item>
			</u-form>
		</view>

		<view class="u-p-30">
			<u-button type="primary" hover-class="none" :loading="loading"
				@click="submitHandle">{{formId?'重新发布':demForm.type?`￥${demForm.price||'0.00'}支付并发布`:'确定发布'}}</u-button>
		</view>
		<!-- 从业年限 -->
		<u-picker mode="selector" :range="expList" v-model="expPicker" title="从业经验要求" :confirm-color="$appConfig.mainColor"
			@confirm="confirmExp" range-key="name"></u-picker>
		<!-- 行业 -->
		<!-- <bb-picker title="所属行业" type="selector" v-model="classPicker" :classOneID="demForm.class_one_id"
			:classTwoId="demForm.class_two_id" @confirm="confirmClass"></bb-picker> -->
		<u-picker mode="selector" :range="classList" v-model="classPicker" title="选择行业" :default-selector="defaultClass"
			:confirm-color="$appConfig.mainColor" @confirm="confirmClass" range-key="name"></u-picker>
		<!-- 标签 -->
		<u-popup v-model="tagsPicker" mode="bottom" border-radius="20" :mask-close-able="false"
			:safe-area-inset-bottom="true">
			<view class=" u-border-bottom u-flex u-row-between" style="padding: 25rpx 35rpx;">
				<text class="u-tips-color" @click="tagsPicker=false">取消</text>
				<view class="u-font-32 ">
					选择服务标签(多选)
				</view>
				<view class="u-type-primary" @click="comfimTag">确认</view>
			</view>
			<view class="tag-content">
				<view class="tag-item" :class="[selectTags.includes(item)?'active':'']" v-for="(item,index) in tagList"
					:key="index" @click="selectTagesHandle(index)">{{item.name}}</view>
			</view>
		</u-popup>
		<!-- 时间选择 -->
		<u-picker v-model="timePicker" mode="time" :defaultTime="demForm.serve_time" :safe-area-inset-bottom="true"
			:params="{year:true,month:true,day:true,hour:true,minute:true}" :confirm-color="$appConfig.mainColor"
			:start-year="timeStartYear" @confirm="confirmTime"></u-picker>
		<bb-payment v-model="showPayType" :orderInfo="orderDetail.order_info" @complate="queryOrderDetail"></bb-payment>
	</view>
</template>

<script>
	export default {
		name: "xuqiu",
		data() {
			return {
				showPayType:false,
				orderDetail:{},
				demForm: {
					title: '',
					price: '',
					description: '',
					class_one_name: '',
					class_one_id: '',
					address: '',
					lng: '',
					lat: '',
					exp_name: '1年以上',
					exp_id: 1,
					serve_time: '',
					image: [],
					type:0
				},
				demForm_image: [],
				rules: {
					title: [{
						required: true,
						message: '请填写需求标题'
					}],
					price: [{
							required: true,
							transform(value) {
								return String(value)
							},
							message: '请填出价金额'
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.amount(value);
							},
							message: '请填正确的金额数值'
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.range(Number(value), [this.$appConfig.MIN_PRICE, this.$appConfig.MAX_PRICE])
							},
							message: `金额必须为${this.$appConfig.MIN_PRICE}~${this.$appConfig.MAX_PRICE}元以内`
						}
					],
					description: [{
						required: true,
						message: '请填写需求内容'
					}],
					class_one_name: [{
						required: true,
						message: '请选择所属行业'
					}],
					address: [{
						required: true,
						message: '请填写服务地址'
					}],
					exp_name: [{
						required: true,
						message: '请选择从业经验要求'
					}],
					serve_time: [{
						required: true,
						message: '请填写服务时间'
					}]
				},
				classPicker: false,
				tagsPicker: false,
				expPicker: false,
				timePicker: false,
				className: '',
				expList: [],
				tagList: [],
				selectTags: [],
				loading: false,
				formId: '',
				classList: [],
				defaultClass: [0],
				config: this.$appConfig,
				isDisabled:false
			}
		},
		onReady() {
			this.$refs.demForm.setRules(this.rules)
		},
		onShow() {
			uni.$off('selectLocation')
		},
		onLoad(e) {
			if (e.id) {
				this.formId = e.id;
			}
			this.queryExpOption()
			this.queryClassOption()
		},
		computed: {
			timeStartYear() {
				const nowDay = new Date();
				return nowDay.getFullYear()
			}
		},
		methods: {
			// 上傳圖片
			async uploadImageHandle(lists, name) {
				const list = [];
				lists.map(item => {
					if (!item.error) {
						let url = item.response ? item.response.data.url : item.url;
						list.push(url)
					}
				})
				this.demForm[name] = list;
			},
			// 移除圖片
			removeImage(index, list, name) {
				this.demForm[name].splice(index, 1)
			},
			demTypeChange(type){
				if(this.isDisabled){
					this.$u.toast("一口价无法更改！建议您关闭该需求来重新发布")
				}else{
					this.demForm.type = type
				}
			},
			queryDemandDetail() {
				this.$u.api.demandDetail(this.formId).then(res => {
					const keys = Object.keys(this.demForm);
					keys.map(key => {
						this.$set(this.demForm, key, res[key])
					})
					this.demForm_image = res.image.map(item => ({
						url: item
					}))
					this.isDisabled = res.is_pay==1 
					const index = this.classList.findIndex(item => item.id == res.class_one_id)
					this.defaultClass = index ? [index] : [0]
					// this.className = `${res.class_one_name} | ${res.class_two_name}`
				})
			},
			submitHandle() {
				this.$refs.demForm.validate(valid => {
					if (valid) {
						if (this.formId) {
							this.editHandle()
						} else {
							this.addHandle()
						}
					} 
				})
			},
			editHandle() {
				this.loading = true
				this.$u.api.demandEdit(this.formId, this.demForm).then(res => {
					if(this.demForm.type==1 && !this.isDisabled){
						this.orderDetail = res
						this.showPayType = true
					}else{
						this.$u.toast('修改成功!')
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					}
					
				}).finally(() => {
					this.loading = false
				})
			},
			addHandle() {
				
				this.loading = true
				this.$u.api.demandAdd(this.demForm).then(res => {
					if(this.demForm.type==1){
						this.orderDetail = res
						this.showPayType = true
					}else{
						this.$u.toast('发布成功!')
						setTimeout(() => {
							this.pageBack()
						}, 1000)
					}
				}).finally(() => {
					this.loading = false
				})
			},
			
			pageBack() {
				let pages = getCurrentPages();
				if (pages.length >= 2 && pages[pages.length - 2].route === 'pages/subpage/profile/my_demand') {
					uni.navigateBack()
				} else {
					this.$u.route({
						url: '/pages/subpage/profile/my_demand',
						params: {
							status: 0
						},
						type: 'redirectTo'
					})
				}
			},
			// 行业选项
			queryClassOption(pid = 0) {
				this.$u.api.public.industry_class({
					pid: 0
				}).then(res => {
					this.classList = res
					if (this.formId) {
						this.queryDemandDetail()
					}
				})
			},
			confirmClass(e) {
				// this.className = `${e.oneClass.name} | ${e.tags[0].name}`
				// this.demForm.class_one_id = e.oneClass.id
				// this.demForm.class_one_name = e.oneClass.name
				// this.demForm.class_two_id = e.tags[0].id
				// this.demForm.class_two_name = e.tags[0].name
				// this.demForm.class_three_name = '';
				// this.selectTags = [];
				// this.queryTages()
				const index = e[0];
				this.defaultClass = e;
				this.demForm.class_one_id = this.classList[index].id;
				this.demForm.class_one_name = this.classList[index].name
			},
			// 查询标签
			queryTages() {
				this.$u.api.public.industry_class({
					pid: this.demForm.class_two_id
				}).then(res => {
					this.tagList = res
				})
			},
			priceChange(value) {
				if (!this.$u.test.range(Number(value), [this.$appConfig.S_MIN_PRICE, this.$appConfig.S_MAX_PRICE])) {
					this.$u.toast(`金额必须为${this.$appConfig.MIN_PRICE}~${this.$appConfig.MAX_PRICE}元以内`)
				}
			},
			opentagPicker() {
				if (this.demForm.class_two_id) {
					this.tagsPicker = true
				} else {
					this.$u.toast("请选择所属行业")
				}
			},
			comfimTag(e) {
				this.demForm.class_three_id = this.selectTags.map(item => item.id).join(',')
				this.demForm.class_three_name = this.selectTags.map(item => item.name).join(',')
				this.tagsPicker = false
			},
			selectTagesHandle(index) {
				const tag = this.tagList[index];
				const tindex = this.selectTags.findIndex(item => item.id == tag.id)
				if (tindex >= 0) {
					this.selectTags.splice(tindex, 1)
				} else {
					this.selectTags.push(tag)
				}
			},
			// 从业经验选项
			queryExpOption() {
				this.$u.api.public.exp_list().then(res => {
					this.expList = res
				})
			},

			confirmExp(e) {
				const index = e[0]
				this.demForm.exp_id = this.expList[index].id;
				this.demForm.exp_name = this.expList[index].name
			},
			// 地址选择
			chooseAddress() {
				uni.$on('selectLocation', (data) => {
					console.log(data);
					const {
						province,
						city,
						district,
						street,
						location
					} = data
					this.demForm.address = street
					this.demForm.lng = location.split(',')[0]
					this.demForm.lat = location.split(',')[1]
				})
				this.$u.route('/pages/subpage/list/location')
			},
			// 时间选择
			confirmTime(e) {
				this.demForm.serve_time = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}`
			},
			queryOrderDetail(){
				this.showPayType = false
				this.$u.toast('发布成功!')
				setTimeout(() => {
					this.pageBack()
				}, 1000)
			}
		}
	}
</script>

<style scoped lang="scss">
	.page-view {
		margin-top: 30rpx;
		background-color: #fff;
	}

	.input-box {
		height: 88rpx;
		background: #F6F6F6;
		border-radius: 60rpx 60rpx 60rpx 60rpx;
		padding: 0 32rpx;
		display: flex;
		align-items: center;
	}

	.u-line {
		width: 0;
		height: 42rpx;
		border-left: 1px solid #D9D9D9;
		margin: 0 20rpx;
	}

	.page-view ::v-deep .u-form-item {
		margin: 0 30rpx;
	}

	.tag-content {
		padding: 30rpx 40rpx 80rpx;
		display: flex;
		flex-wrap: wrap;

		.tag-item {
			padding: 10rpx 20rpx;
			border: 1rpx solid #D9D9D9;
			color: #666666;
			border-radius: 10rpx;
			margin: 10rpx;

			&.active {
				color: $u-type-primary;
				border-color: $u-type-primary;
			}
		}
	}
</style>